package com.aat.dxfy.lucene.dao.impl;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.aat.dxfy.lucene.bean.Article;
import com.aat.dxfy.lucene.dao.IArticleDAO;

public class ArticleDAOImpl implements IArticleDAO {
	
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	private class ArticleRowMapper implements RowMapper<Article> {

		@Override
		public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
			Article article = new Article();
			ResultSetMetaData meta = rs.getMetaData();
			int colNum = meta.getColumnCount();
			for (int i = 1; i <= colNum; i++) {
				String colName = meta.getColumnName(i).toLowerCase();
				if ("title".equals(colName)) {
					article.setTitle(rs.getString(i));
				} else if ("content".equals(colName)) {
					article.setContent(rs.getString(i));
				} else if ("tag".equals(colName)) {
					article.setTag(rs.getString(i));
				}
			}
			return article;
		}

	}
	 

	public List<Article> getArticles() {
		String sql = "SELECT title, tag, content FROM article";
		return (List<Article>) jdbcTemplate.query(sql, new ArticleRowMapper());
		/***
		 List<Article> lists = new ArrayList<>();
		Article a1 = new Article("三国演义", "话说天下大势，分久必合，合久必分。周末七国分争，并入于秦。及秦灭之后，楚、汉分争，又并入于汉。汉朝自高祖斩白蛇而起义，一统天下，后来光武中兴，传至献帝，遂分为三国。推其致乱之由，殆始于桓、灵二帝。桓帝禁锢善类，崇信宦官。及桓帝崩，灵帝即位，大将军窦武、太傅陈蕃共相辅佐。时有宦官曹节等弄权，窦武、陈蕃谋诛之，机事不密，反为所害，中涓自此愈横。", "小说,名著");
		Article a2 = new Article("三国志", "发矫诏诸镇应曹公　破关兵三英战吕布", "三国");
		Article a3 = new Article("关云长", "美髯公千里走单骑　汉寿侯五关斩六将", "关羽");
		
		lists.add(a1);
		lists.add(a2);
		lists.add(a3);
		return lists;
		 */
	}


	public int addArticle(Article a) {
		String sql = "INSERT INTO article (title, tag, content) VALUES(?,?,?)";
		return jdbcTemplate.update(sql, a.getTitle(),a.getTag(),a.getContent());
	}

}